<template>
    <div class="main_container">
        <div class="tops">
            <div v-for="item in accounts" :key="'acc_'+item.id" class="item">
                <span style="font-size: 14px;color: #606266;">{{ item.name+':' }}</span>
                
                <el-popover v-if="!item.edit" placement="bottom" trigger="hover">
                    <div style="text-align: center;cursor: pointer;height: 36px;line-height: 36px;" @click="changeMoney(item)">修改金额</div>
                    <div class="common_line"></div>
                    <div style="text-align: center;cursor: pointer;height: 36px;line-height: 36px;" @click="transferMoney(item)">账户转账</div>
                    <span class="total" :style="{color: item.money<0?'red':'#333'}" slot="reference">{{ '￥'+item.money.toFixed(2) }}</span>
                </el-popover>
                <el-input v-else v-model="item.money" placeholder="请输入金额" style="width: 150px;"
                    @blur="accountBlur($event, item)" maxlength="20" clearable></el-input>
            </div>
        </div>
        <pie-chart :pieData="chartData" :customStyle="customStyle" :showLegend="true" :totalValue="totalValue"></pie-chart>

        <el-row style="height: 40px;line-height: 40px;margin: 30px 20px 25px 20px;">
            <el-col :span="5">
                <el-radio-group v-model="filterType" @change="radioChange">
                    <el-radio label="1">按条件筛选</el-radio>
                    <el-radio label="2">按日期范围</el-radio>
                </el-radio-group>
            </el-col>
            <el-col :span="6" v-if="filterType=='1'">
                <el-select style="width: 240px;" v-model="date_order_type" placeholder="请选择"
                    @change="typeChange">
                    <el-option v-for="item in filterTypes" :key="'filter_'+item.value" 
                        :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-col>
            <el-col :span="6" v-else>
                <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" 
                    v-model="dateRange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
                    :picker-options="handleTime" @change="dateChange"
                    placeholder="请选择日期范围" style="width: 240px;" clearable></el-date-picker>
            </el-col>
            <el-col :span="6">
                <span style="font-size: 14px;">账户：</span>
                <el-select style="width: 240px;" v-model="params.pay_type" placeholder="请选择" @change="getData">
                    <el-option v-for="item in payTypes" :key="'pay_'+item.value" 
                        :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-col>
        </el-row>
       
        <div class="common_line"></div>
        <div id="printcontent">
            <el-row style="padding: 5px 10%;">
                <el-col :span="6">
                    <span class="top_title">收入：￥</span>
                    <span class="money" :class="totalData.receive_gap<0?'red':'green'">{{ totalData.receive_gap }}</span>
                </el-col>
                <el-col :span="6">
                    <span class="top_title">支出：￥</span>
                    <span class="money" :class="totalData.payment_gap<0?'red':'green'">{{ totalData.payment_gap }}</span>
                </el-col>
                <el-col :span="6">
                    <span class="top_title">期初：￥</span>
                    <span class="money" :class="totalData.start_money<0?'red':'green'">{{ totalData.start_money }}</span>
                </el-col>
                <el-col :span="6">
                    <span class="top_title">期末：￥</span>
                    <span class="money" :class="totalData.end_money<0?'red':'green'">{{ totalData.end_money }}</span>
                </el-col>
            </el-row>
            <div class="common_line"></div>
            <el-table border :data="tableData" v-loading="loading" show-summary :summary-method="getSummaries" style="margin-top: 15px;">
                <el-table-column label="流水单号" align="center" prop="corp_order_no" />
                <el-table-column label="金额" align="center" prop="order_price" />
                <el-table-column label="单据类型" align="center" prop="flowTitle" />
                <el-table-column label="单据单号" align="center" prop="order_corp_order_no" />
                <el-table-column label="结算账户" align="center" prop="pay_type_str" />
                <el-table-column label="日期" align="center" prop="order_no_date" />
                <el-table-column label="操作" width="120" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            @click="toDetail(scope.row)"
                            style="font-weight: bold;color: #0099ff;"
                        >单据详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-show="total>0"
                background
                style="padding: 32px 16px;background: #fff;text-align: right;"
                @size-change="handleSizeChange"
                @current-change="getNextPageList"
                :current-page.sync="pageParam.page"
                :page-size="pageParam.num"
                layout="total, prev, pager, next, sizes, jumper"
                :page-sizes="[10, 20, 50, 100]"
                :total="total">
            </el-pagination>
        </div>

        <!-- 转账单 -->
        <el-dialog
            title="新增转账单"
            :visible.sync="showTransferPop"
            width="30%"
            :close-on-click-modal="false"
            append-to-body
            center>
            <div style="padding-left: 20px;">
                <el-form :model="transferForm" label-width="auto" ref="transferForm" :rules="rules">
                    <el-row>
                        <el-form-item label="转账金额:" prop="current_paid_payment">
                            <el-input style="width: 240px;" maxlength="100" v-model="transferForm.current_paid_payment" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="时间:" prop="order_no_date">
                            <el-date-picker v-model="transferForm.order_no_date" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                style="width: 240px" placeholder="请选择日期" ></el-date-picker>
                        </el-form-item> 
                    </el-row>
                    <el-row>
                        <el-form-item label="转出账户:">
                            <div>{{ fromPayTypeName }}</div>
                        </el-form-item> 
                    </el-row>
                    <el-row>
                        <el-form-item label="转入账户:" prop="to_type">
                            <el-select style="width: 240px;" v-model="transferForm.to_type" placeholder="请选择" clearable>
                                <el-option v-for="item in payTypes" :key="'pay_'+item.value" 
                                    :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="备注:">
                            <el-input maxlength="200" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 6 }"
                                 v-model="transferForm.remark" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-row>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="showTransferPop=false">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="addTransferOrder">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getAccountList, updateAccount, transferAccount, getFlowReport, getFlowList } from '@/api/statistics'
import pieChart from '@/components/pieChart';
const moment = require('moment')

export default {
    name: 'flowRecords',
    components: {
        pieChart
    },
    data() {
        return {
            showTransferPop: false,
            accounts: [
                {id: 2, name: '微信', money: 0, edit: false},
                {id: 1, name: '现金', money: 0, edit: false},
                {id: 5, name: '支付宝', money: 0, edit: false},
                {id: 3, name: '银行转账', money: 0, edit: false},
                {id: 4, name: '其他', money: 0, edit: false},
            ],
            filterType: '1',  //1 按条件  2 按日期范围
            filterTypes: [
                {id: 1, label: '今日', value: 'cur_day'},
                {id: 2, label: '本周', value: 'cur_weak'},
                {id: 3, label: '本月', value: 'cur_month'},
                {id: 4, label: '本年', value: 'cur_year'}
            ],
            payTypes: [
                {label: '所有账户', value: ''},
                {label: '微信', value: 2},
				{label: '支付宝', value: 5},
				{label: '现金', value: 1},
				{label: '银行转账', value: 3},
				{label: '其他', value: 4}
            ],
            params: {
                corp: '',
                start_date: '',
                end_date: '',
                date_order_type: 'cur_month',
                pay_type: ''
            },
            loading: false,
            pageParam: {
                page: 1,
                num: 10
            },
            total: 0,
            totalLists: [],
            transferForm: {
                corp_id: '',
                from_type: '',
                to_type: '',
                current_paid_payment: '',
                order_no_date: '',
                remark: ''
            },
            date_order_type: 'cur_month',
            tableType: 'income',
            dateRange: [],
            handleTime: {
                disabledDate(date) {
                    //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
                    return date.getTime() > Date.now();
                }
            },
            customStyle: {
                width: '600px',
                height: '300px',
                paddingRight: '74px'
            },
            totalData: {
                receive_gap: 0,  //收入
                payment_gap: 0,  //支出
                start_money: 0,  //期初
                end_money: 0  //期末
            },
            totalValue: 0,
            tableData: [],
            chartData: [],
            rules: {
                current_paid_payment: [
                    { required: true, message: "请输入转账金额", trigger: "blur" },
                ],
                order_no_date: [
                    { required: true, message: "请选择时间", trigger: "change" },
                ],
                to_type: [
                    { required: true, message: "请选择转入账户", trigger: "change" },
                ],
            },
            fromPayTypeName: ''
        }
    },
    created() {
        this.params.corp = this.$store.state.corpId
        let nowDate = new Date()
        this.params.start_date = nowDate.getFullYear()+'-01-01'
        this.getTotalData()
        // this.getData()
        this.typeChange(this.date_order_type)
    },
    methods: {
        // 补零
        add0(num) {
            if (parseInt(num) < 10){
                num = '0'+ num
            }
            return num
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                    }, 0);
                    sums[index] = sums[index].toFixed(2);
                } else {
                    sums[index] = '--';
                }
            });

            return sums;
        },
        // 获取总数据
        getTotalData() {
            getAccountList({
                corp: this.params.corp
            }).then(res => {
                let chartDatas = []
                res.data.forEach(item => {
                    this.accounts.forEach(_item => {
                        if (_item.id === item.pay_type) {
                            _item.money = parseFloat(item.current_money)
                        }
                    })
                    if (parseFloat(item.current_money) >= 0){  //亏损的不展示
                        chartDatas.push({
                            name: item.pay_type_str,
                            value: parseFloat(item.current_money)
                        })
                    }
                    this.totalValue = item.pay_type===100?item.current_money:0
                })
                this.chartData = chartDatas
            })
        },
        transferMoney(item) {
            this.transferForm.corp_id = this.params.corp
            this.transferForm.from_type = item.id
            this.fromPayTypeName = item.name
            this.transferForm.order_no_date = moment().format('yyyy-MM-DD')
            this.showTransferPop = true
        },
        addTransferOrder() {
            let that = this
            that.$refs['transferForm'].validate(valid => {
                if(!valid) return

                transferAccount(that.transferForm).then(res => {
                    if (res.code == 200) {
                        that.$message({
                            message: '转账成功',
                            type: 'success'
                        })
                        that.getTotalData()
                    }
                    that.showTransferPop = false
                })
            })
        },
        accountBlur(val, item) {
            let value = val.target.value
            value = value.replace(/^(?!-)([^-\d.])/g, ''); // 只允许负号、数字和小数点
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            this.accounts.forEach(_item => {
                _item.edit = false
                if (_item.id === item.id){
                    _item.money = parseFloat(value)
                }
            })

            // 修改余额
            updateAccount({
                pay_type: item.id,
                current_money: parseFloat(value),
                corp_id: this.params.corp
            }).then(res => {
                if(res.code == 200) {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    })
                    this.getTotalData()
                }
            })
        },
        changeMoney(item) {
            return item.edit = !item.edit
        },
        // 获取数据
        getData() {
            var that = this
            that.loading = true
            // 获取汇总数据
            getFlowReport({
                corp: this.params.corp,
                pay_type: this.params.pay_type,
                date_order_type: this.params.date_order_type,
                start_date: this.params.start_date,
                end_date: this.params.end_date
            }).then(res => {
                if (res.code == 200){
                    this.totalData.receive_gap = res.data.receive_gap.toFixed(2)
                    this.totalData.payment_gap = res.data.payment_gap.toFixed(2)
                    this.totalData.start_money = res.data.start_money.toFixed(2)
                    this.totalData.end_money = res.data.end_money.toFixed(2)
                }
            })
            
            // 获取流水列表
            getFlowList(that.params).then(res => {
                if (res.code == 200){
                    let lists = res.data.instance_list.filter(item => {
                        let txt = '', pageUrl = '', param = {};
                        switch (item.pay_record_type){
                            case 1:  //日常收支
                                txt = item.expenditure_detail.category_detail?item.expenditure_detail.category_detail.name:'日常收支'
                                pageUrl = 'expensesList'
                                param = { bussId3: item.expenditure }
                                break;
                            case 2:  //采购
                                txt = item.record_type===1?'采购单收入':'采购单支出'
                                pageUrl = 'purchaseOrder'
                                param = { bussId5: item.purchase }
                                break;
                            case 3:  //采购预定
                                txt = item.record_type===1?'采购预订收入':'采购预订支出'
                                pageUrl = 'purchaseReserve'
                                param = { bussId6: item.reserve_purchase }
                                break;
                            case 4:  //销售
                                txt = item.record_type===1?'销售单收入':'销售单支出'
                                pageUrl = 'saleOrder'
                                param = { bussId8: item.sale_order }
                                break;
                            case 5:  //销售退单
                                txt = item.record_type===1?'销售退单收入':'销售退单支出'
                                pageUrl = 'saleReturn'
                                param = { bussId: item.sale_return }
                                break;
                            case 6:  //销售预定
                                txt = item.record_type===1?'销售预订收入':'销售预订支出'
                                pageUrl = 'saleReserve'
                                param = { bussId9: item.reserve_order }
                                break;
                            case 7:  //账户转账
                                txt = item.record_type===1?'账户转账收入':'账户转账支出'
                                break;
                            case 8:  //采购退单
                                txt = item.record_type===1?'采购退单收入':'采购退单支出'
                                pageUrl = 'purchaseReturn'
                                param = { bussId7: item.pu_return }
                                break;
                            case 9:  //商品拆分
                                txt = item.record_type===1?'商品拆分收入':'商品拆分支出'
                                pageUrl = 'joinSplit'
                                param = { bussId4: item.stock_split, type: 'split' }
                                break;
                            case 10:  //商品合并
                                txt = item.record_type===1?'商品组装收入':'商品组装支出'
                                pageUrl = 'joinSplit'
                                param = { bussId4: item.stock_join, type: 'join' }
                                break;
                            case 11:  //客户收款单
                                txt = item.record_type===1?'客户收款单收入':'客户收款单支出'
                                pageUrl = 'receiveOrder'
                                param = { bussId2: item.receipt_payment }
                                break;
                            case 12:  //供货商付款单
                                txt = item.record_type===1?'供货商付款单收入':'供货商付款单支出'
                                pageUrl = 'payOrder'
                                param = { bussId1: item.bills_payment }
                                break;
                            default:
                                break;
                        }
                        item.flowTitle = txt
                        item.pageUrl = pageUrl
                        item.param = param
                        item.order_price = item.show_updated_paid_payment.toFixed(2)
                        return item
                    })
                    that.totalLists = lists
                    that.total = lists.length
                    that.pageParam.page = 1
                    that.getNextPageList()
                    that.loading = false
                }
            })
        },
        handleSizeChange(val) {
            this.pageParam.num = val
            this.getNextPageList()
        },
        getNextPageList() {
            let totalPage = 0  //总页数
            if (this.total % this.pageParam.num === 0){  //整除
                totalPage = Math.trunc(this.total / this.pageParam.num)
            }else{
                totalPage = Math.trunc(this.total / this.pageParam.num) + 1
            }

            function chunkArray(arr, size) {
                const result = [];
                for (let i = 0; i < arr.length; i += size) {
                    result.push(arr.slice(i, i + size));
                }
                return result;
            }

            if (this.pageParam.page <= totalPage){
                let groups = chunkArray(this.totalLists, this.pageParam.num)
                this.tableData = groups[this.pageParam.page-1]
            }else{
                this.tableData = []
            }
        },
        radioChange(val) {
            if (val == '1'){
                this.typeChange(this.date_order_type)
            }else{
                this.dateChange(this.dateRange)
            }
        },
        typeChange(val) {
            let nowDate = new Date()
            if (val.indexOf("cur_")<0){
                this.params.start_date = nowDate.getFullYear()+'-01-01'
                if(val == 'day'){  //本月，28~31天
                    this.params.start_date = nowDate.getFullYear()+this.add0(nowDate.getMonth()+1)+'-01'
                }
            }else{
                this.params.start_date = ''
            }
            this.params.date_order_type = val

            this.getData()
        },
        dateChange(value) {
            if(value && value.length){
                this.params.start_date = value[0]
                this.params.end_date = value[1]
                this.params.date_order_type = 'customize_date'
                this.getData()
            }else{
                this.params.start_date = this.params.end_date = null
                this.params.date_order_type = ''
                this.tableData = []
                this.totalData = {
                    receive_gap: 0,  //采购支出
                    payment_gap: 0,  //日常支出
                    start_money: 0,  //营业额
                    end_money: 0  //利润
                }
            }
        },
        toDetail(item) {
            if (item.pageUrl){
                this.$router.push({
                    path: item.pageUrl,
                    query: item.param
                })
            }
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../style/mixin.less';
    .tops {
        display: flex;
        align-items: center;
        width: 100%;
        padding: 10px 0;
        .item {
            width: 25%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            .total{
                cursor: pointer;
            }
        }
    }
    .btns {
        float: right;
        height: 40px;
        display: flex;
        align-items: center;
        padding-right: 20px;
    }
    .top_title {
        font-size: 14px;
        color: #606266;
    }
    .money {
        font-size: 20px;
        // color: red;
    }
    .red {
        color: red;
    }
    .green {
        color: @blue;
    }
</style>